<template>
  <Dialog width="1000px" :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="scoreFormRef"
      :model="formData"
      label-width="300px"
      v-loading="formLoading"
      label-position="top"
    >
      <div v-for="(item, index) in formData" :key="item.id">
        <p>
          {{index + 1}}. 区域: {{ item.name }}, (总分：{{ item.score }}分),
        </p>

        <div style="margin:10px;">
          <div v-for="(detail, index2) in item.cleaningAreaDetailDOList" :key="detail.id">

            <p>
              <span style="font-weight: bold; margin-top: 20px;">
                检查内容：
              </span>
              {{ detail.content }}
            </p>
            <p>

              <span v-html="detail.inspectionSpec"></span>

              <span style="font-weight: bold; margin-top: 20px;">
                扣分详细：
              </span>
              {{ detail.pointSpec }}
            </p>
            <div style="margin: 10px">
              进行打分：
              <el-input-number
                v-model="submitFormData[index].cleaningAreaDetailDOList[index2].score"
                :step="submitFormData[index].cleaningAreaDetailDOList[index2].score_step"
                :min="0" :max="detail.score" />
              <Editor height="150px" />
            </div>

          </div>
        </div>

      </div>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ProjectApi } from '@/api/project/project'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗是否展示
const dialogTitle = ref('') // 弹窗标题
const formLoading = ref(false) // 表单加载状态
const formType = ref('') // 表单类型：create - 新增；update - 修改
const projectId = ref(0)
const assessmentBatchId = ref(0)
const formData = ref<{
  id: number;
  name: string;
  score: number;
  cleaningAreaDetailDOList: {
    id: number;
    content: string;
    score: number;
    inspectionSpec: string;
    pointSpec: string;
  }[];
}[]>([])

const submitFormData = ref<{
  id: number;
  name: string;
  score: number;
  cleaningAreaDetailDOList: {
    record_id: number,
    id: number;
    content: string;
    score: number;
    inspectionSpec: string;
    pointSpec: string;
    score_step: number;
    remark: string;
  }[];
}[]>([])

// 用于存储总得分
let totalScore = ref(0)
let allAreaScore = ref(0)
const scoreFormRef = ref()



/** 打开弹窗 */
const open = async (type: string, curProjectId: number, curAssessmentBatchId: number) => {

  allAreaScore.value = 0 // bug

  dialogVisible.value = true
  dialogTitle.value = `${t('action.' + type)}打分`
  formType.value = type
  resetForm()
  formLoading.value = true

  projectId.value = curProjectId
  assessmentBatchId.value = curAssessmentBatchId
  // console.log("type", type)
  let preScoreData: any = {};
  if (type === 'update') {
    preScoreData = await ProjectApi.getPreCleanAreaRecord(curProjectId, curAssessmentBatchId)
    console.log('preScoreData', preScoreData)
  }

  try {
    const response = await ProjectApi.getCleanScoreList()
    formData.value = response || []
    if (formData.value) {
      submitFormData.value = response.map(item => {
        allAreaScore.value += item.score

        console.log("item", item)
        let list = item.cleaningAreaDetailDOList.map(detail => {
          // 在 preScoreData 中查找与当前 item.id 对应的 areaId
          let matchingPreScore = undefined
          if (type === 'update') {
            matchingPreScore = preScoreData.find(
              (preScore: any) => preScore.cleaningAreaDetailId === detail.id
            );
          }

          return {
            record_id: matchingPreScore ? matchingPreScore.id : "",
            id: detail.id,
            content: detail.content,
            score: matchingPreScore ? matchingPreScore.score : detail.score,
            inspectionSpec: detail.inspectionSpec,
            pointSpec: detail.pointSpec,
            score_step: detail.pointSpec.match(/\d+(\.\d+)?/) ? parseFloat(detail.pointSpec.match(/\d+(\.\d+)?/)[0]) : 1,
            remark: matchingPreScore ? matchingPreScore.remark : "",
          }
        })

        return {
          id: "",
          name: item.name,
          score: item.score,
          cleaningAreaDetailDOList: list,
        }
      });
      console.log('submitFormData', submitFormData.value)

    }
    // updateTotalScore() // 初始化总分
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件
const submitForm = async () => {
  try {
    await scoreFormRef.value?.validate()
    formLoading.value = true
    if (formType.value === 'create') {
      // await ProjectApi.createCheckRecord(submitFormData.value)
      // message.success(t('common.createSuccess'))
    } else {
      // await ProjectApi.updateCheckRecord(submitFormData.value)
      // message.success(t('common.updateSuccess'))
    }
    console.log('submitFormData', submitFormData.value)


    // 处理submitFormData 让他变成传给后端的数据
    const lastFormData = ref<{
      id: number;
      projectId : number;
      assessmentBatchId: number;
      cleaningAreaDetailId: number;
      score: number;
      remark: string;
    }[]>([])
    submitFormData.value.forEach(item => {
      item.cleaningAreaDetailDOList.forEach(detail => {
        totalScore.value += detail.score
        lastFormData.value.push({
          id: detail.record_id,
          projectId: projectId.value,
          assessmentBatchId: assessmentBatchId.value,
          cleaningAreaDetailId: detail.id,
          score: detail.score,
          remark: detail.remark
        })
      })
    })
    console.log('lastFormData', lastFormData)

    dialogVisible.value = false
    emit('success', lastFormData.value, totalScore, allAreaScore)
  } catch (error) {
    console.error(error)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = []
  submitFormData.value = []
  totalScore.value = 0
  scoreFormRef.value?.resetFields()
}
</script>
